#include <string.h>
#include <stdio.h>
#include "utils.h"

// Replace / with '+#sl+'. This is needed to sneak / characters past Tomcat.
// It is based on the assumption that the string will be enclosed in
// single quotes.
int escape_forward_slash(char* dst, size_t dstlen, const char* src) {
  for (;; src++) {
    const char c = *src;
    if (c == '\0') {
      if (dstlen < 1) {
        return -1;
      }
      *dst = '\0';
      return 0;
    } else if (c == '/') {
      if (dstlen < 7) {
        return -1;
      }
      memcpy(dst, "'+#sl+'", 7);
      dst += 7;
      dstlen -= 7;
    } else {
      if (dstlen < 1) {
        return -1;
      }
      *dst = c;
      dst++;
      dstlen--;
    }
  }
}

int urlencode(char* dst, size_t dstlen, const char* src) {
  for (;; src++) {
    const char c = *src;
    if (c == '\0') {
      if (dstlen < 1) {
        return -1;
      }
      *dst = '\0';
      return 0;
    } else if (('a' <= c && c <= 'z') ||
	       ('A' <= c && c <= 'Z') ||
	       ('0' <= c && c <= '9') ||
	       c == '-' || c == '_' || c == '.' || c == '~') {
      if (dstlen < 1) {
        return -1;
      }
      *dst = c;
      dst++;
      dstlen--;
    } else {
      if (dstlen < 3) {
        return -1;
      }
      sprintf(dst, "%%%.2x", c);
      dst += 3;
      dstlen -= 3;
    }
  }
}
